#include "stdafx.h"
#include "net/OAuth20Credentials.hpp"
#include "stdlib/exception.hpp"
using JHCPP::stdlib::jhException::NotAuthenticatedException;

NET_NAMESPACE_BEGIN

const std::string COAuth20Credentials::SCHEME = "Bearer";

COAuth20Credentials::COAuth20Credentials() : m_scheme(SCHEME)
{
}

COAuth20Credentials::COAuth20Credentials(const std::string& bearerToken)
	: m_bearerToken(bearerToken),
	m_scheme(SCHEME)
{
}

COAuth20Credentials::COAuth20Credentials(const std::string& bearerToken, const std::string& scheme)
	: m_bearerToken(bearerToken),
	m_scheme(scheme)
{
}

COAuth20Credentials::COAuth20Credentials(const CHTTPRequest& request) : m_scheme(SCHEME)
{
	extractBearerToken(request);
}

COAuth20Credentials::COAuth20Credentials(const CHTTPRequest& request, const std::string& scheme) : m_scheme(scheme)
{
	extractBearerToken(request);
}

COAuth20Credentials::~COAuth20Credentials()
{
}

void COAuth20Credentials::setBearerToken(const std::string& bearerToken)
{
	m_bearerToken = bearerToken;
}

const std::string& COAuth20Credentials::getBearerToken() const
{
	return m_bearerToken;
}

void COAuth20Credentials::setScheme(const std::string& scheme)
{
	m_scheme = scheme;
}

const std::string& COAuth20Credentials::getScheme() const
{
	return m_scheme;
}

void COAuth20Credentials::authenticate(CHTTPRequest& request)
{
	std::string auth(m_scheme);
	auth += ' ';
	auth += m_bearerToken;
	request.set(CHTTPRequest::AUTHORIZATION, auth);
}

void COAuth20Credentials::extractBearerToken(const CHTTPRequest& request)
{
	if (request.hasCredentials())
	{
		std::string authScheme;
		std::string authInfo;
		request.getCredentials(authScheme, authInfo);
		if (icompare(authScheme, m_scheme) == 0)
		{
			m_bearerToken = authInfo;
		}
		else throw NotAuthenticatedException("No bearer token in Authorization header", authScheme);
	}
	else throw NotAuthenticatedException("No Authorization header found");
}

NET_NAMESPACE_END
